package com.translate.web.service.impl;

import com.translate.entity.Banner;
import com.translate.vo.contract.IBannerVO;
import com.translate.web.config.contract.IOSSConfig;
import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.BannerMapper;
import com.translate.web.service.IBannerService;
import com.basic.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class BannerServiceImpl extends BaseServiceImpl<Banner> implements IBannerService {
	
	private IOSSConfig config;
	
	
	private RedisTemplate<String, List<Banner>> redisTemplate;
	
	
	
	public BannerServiceImpl(BannerMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Banner data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Banner data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	protected Class<Banner> getEntityClass() {
		return Banner.class;
	}

	@Override
	public <VO extends IBannerVO> List<VO> bannerVOsFormCache(Class<VO> target) {
		
		ValueOperations<String, List<Banner>> opsForValue = this.redisTemplate.opsForValue();
		
		List<Banner> list = opsForValue.get(RedisConstant.BANNER_KEY);
		
		if (null != list) {
			return this.entityConvertToVo(list, target);
		}
		
		list = this.getBannerOpenEnable();
		
		if (0 == list.size()) {
			opsForValue.set(RedisConstant.BANNER_KEY, list, 3, TimeUnit.SECONDS);
			
			return new ArrayList<VO>(0);
		}
		
		String url = "https://".concat(config.getBucketName()).concat(".").concat(config.getEndpoint());
		
		for (Banner banner : list) {
			banner.setPicUrl(url.concat(banner.getPicUrl()));
		}
		
		opsForValue.set(RedisConstant.BANNER_KEY, list, 15, TimeUnit.SECONDS);
		
		return this.entityConvertToVo(list, target);
	}
	
	protected List<Banner> getBannerOpenEnable() {
		
		return ((BannerMapper)this.mapper).getBannersForEnabled();
		
	}

	@Resource
	public void setRedisTemplate(RedisTemplate<String, List<Banner>> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	@Resource
	public void setConfig(IOSSConfig config) {
		this.config = config;
	}
}